<template>
  <el-dialog :visible.sync="show" title="批量设置" center width="fit-content" :before-close="cancel"
    :close-on-click-modal="false">
    <div>
      <div class="item">
        <div class="label">
          选择设置类型：
        </div>
        <div class="value">
          <el-select v-model="type" clearable filterable placeholder="请选择设置类型" @change="handleTypeChange">
            <el-option v-for="item in typeList" :value="item.id" :label="item.name" :key="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="item" v-show="type == 1">
        <div class="label">
          是否需要配送费：
        </div>
        <div class="value">
          <el-radio v-model="deliveryFlag" :label="1">是</el-radio>
          <el-radio v-model="deliveryFlag" :label="0">否</el-radio>
        </div>
      </div>
      <div class="item" v-show="type == 2">
        <div class="label">
          包装费计算方式：
        </div>
        <div class="value">
          <el-radio v-model="packageFlag" :label="1">独立包装费</el-radio>
          <el-radio v-model="packageFlag" :label="2">合并包装费</el-radio>
        </div>
      </div>
      <div class="item" v-show="type == 3">
        <div class="label">
          包装费：
        </div>
        <div class="value">
          <el-input v-maxnum="{ obj: $data, key: 'packageFee', zero: true, length: 2 }" v-model="packageFee">
            <div slot="append">元</div>
          </el-input>
        </div>
      </div>
      <div class="item" v-show="type == 4 && showStock">
        <div class="label">
          库存：
        </div>
        <div class="value">
          <el-input v-maxnum="{ obj: $data, key: 'stock', int: true, zero: true }" v-model="stock"></el-input>
        </div>
      </div>
      <div class="item" v-show="type == 5 && businessId">
        <div class="label">
          部门：
        </div>
        <div class="value">
          <el-cascader style="width: 100%;" v-model="departIds" placeholder="请选择部门" :options="departList" :props="{
            label: 'departName',
            value: 'departId',
            checkStrictly: true,
          }">
          </el-cascader>
        </div>
      </div>
      <div class="item" v-show="type == 6 && businessId">
        <div class="label">
          商户分类：
        </div>
        <div class="value">
          <el-select class="business-classify_select" style="width: 100%;" v-model="classifyIds" placeholder="请选择商户分类"
            multiple @change="handleClassifyChange" filterable clearable
            v-selectrichtext="{ ids: classifyIds, list: businessClassifylist }">
            <el-option v-for="item in businessClassifylist" :value="item.id" :label="item.name" :key="item.id">
              <div class="business-classify_name" v-html="item.name"></div>
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="item" v-show="type == 7">
        <div class="label">
          送货方式：
        </div>
        <div class="value">
          <el-select v-model="deliveryWay" clearable placeholder="请选择">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div v-show="type == 8">
        <div class="item">
          <div class="label">
            养老金最高抵扣额比例：
          </div>
          <div class="value">
            <el-input type="number" v-model="discountOld" @blur="numberVerify(1)">
              <div slot="append">%</div>
            </el-input>
          </div>
        </div>
        <div class="item">
          <div class="label">
            养老金返利比例：
          </div>
          <div class="value">
            <el-input type="number" v-model="rebateOld" @blur="numberVerify(3)">
              <div slot="append">%</div>
            </el-input>
          </div>
        </div>
        <div class="item">
          <div class="label">
            物业金最高抵扣额比例：
          </div>
          <div class="value">
            <el-input type="number" v-model="discountPmc" @blur="numberVerify(2)">
              <div slot="append">%</div>
            </el-input>
          </div>
        </div>
        <div class="item">
          <div class="label">
            物业金返利比例：
          </div>
          <div class="value">
            <el-input type="number" v-model="rebatePmc" @blur="numberVerify(4)">
              <div slot="append">%</div>
            </el-input>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button type="primary" @click="confirm">
        确定
      </el-button>
      <el-button @click="cancel">
        取消
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import BusinessServerApi from "@/api/goods/businessServer";
import BusinessDepartApi from "@/api/business/depart";
export default {
  props: {
    show: {
      type: Boolean,
    },
    list: {
      type: Array,
      default: () => [],
    },
  },
  model: {
    prop: "show",
    event: "showDialog",
  },
  data() {
    return {
      deliveryFlag: 1,
      packageFlag: 1,
      packageFee: "",
      discountOld: '',
      discountPmc: '',
      rebateOld: '',
      rebatePmc: '',
      stock: "",
      departIds: [],
      classifyIds: [],
      type: "",
      deliveryWay: '',
      typeList: [
        { id: 1, name: "是否需要配送费" },
        { id: 2, name: "包装费计算方式" },
        { id: 3, name: "设置包装费" },
        { id: 4, name: "修改库存" },
        { id: 5, name: "设置部门" },
        { id: 6, name: "设置商户分类" },
        { id: 7, name: "送货方式" },
        { id: 8, name: "新增补贴金比例" },
      ],
      departList: [],
      businessClassifylist: [],
      listData: [],
      typeOptions: [
        {
          value: "1",
          label: "上门"
        },
        {
          value: "2",
          label: "到店"
        },
        {
          value: "3",
          label: "远程"
        }
      ]
    };
  },
  computed: {
    businessId() {
      return [...new Set(this.listData.map((item) => item.businessId))].length >
        1
        ? ""
        : this.listData[0].businessId;
    },
    showStock() {
      return !this.listData.find((item) => item.variantState !== 1);
    },
  },
  watch: {
    show() {
      Object.assign(this.$data, this.$options.data());
      this.listData = JSON.parse(JSON.stringify(this.list));
    },
  },
  methods: {
    handleTypeChange(type) {
      if ((type == 6 && !this.businessId) || (type == 5 && !this.businessId)) {
        this.type = "";
        return this.$message.error("只能批量设置选相同商户的");
      }
      if (type == 5 && this.departList.length == 0) this.getDepartList();
      if (type == 6 && this.businessClassifylist.length == 0)
        this.getBusienssClassifyList();
      if (type == 4 && !this.showStock) {
        this.type = "";
        return this.$message.error("只能批量设置单品的");
      }
    },
    async getBusienssClassifyList() {
      const res = await BusinessServerApi.classifyListIdName({
        businessId: this.listData[0].businessId,
      });
      console.log(res);
      this.businessClassifylist = res.data || [];
    },
    async getDepartList() {
      const res = await BusinessDepartApi.listMangerTree({
        businessId: this.listData[0].businessId,
      });
      this.setDisabled(res.data);
      this.departList = res.data;
    },
    setDisabled(list) {
      list.forEach((item) => {
        if (!item.power) {
          item.disabled = true;
        }
        if (item.children) {
          this.setDisabled(item.children);
        }
      });
    },
    handleClassifyChange() {
      // this.$nextTick(() => {
      //   const { businessClassifylist, classifyIds } = this;
      //   console.log(classifyIds,businessClassifylist)
      //   const els = document.querySelectorAll(
      //     ".business-classify_select .el-select__tags-text"
      //   );
      //   console.log(els.length)
      //   classifyIds.forEach((item, index) => {
      //     const obj = businessClassifylist.find(item2 => item2.id == item);
      //     els[index].innerHTML = obj.name;
      //   });
      // });
    },
    async confirm() {
      const {
        packageFlag,
        packageFee,
        deliveryFlag,
        type,
        stock,
        departIds,
        classifyIds,
        listData,
        businessId,
        showStock,
        deliveryWay,
        discountOld,
        discountPmc,
        rebateOld,
        rebatePmc,
      } = this;
      if (!this.type) return this.$message.error("请选择类型");
      await this.$confirm("确认保存吗？", "提示", {});
      const serverIds = listData.map((item) => item.serverId);
      let params = {
        type,
        serverIds,
      };
      switch (type) {
        case 1:
          params.value = deliveryFlag;
          break;
        case 2:
          params.value = packageFlag;
          break;
        case 3:
          params.value = packageFee;
          break;
        case 4:
          //   if (!showStock) return this.$message.error("请重新选择单品的产品");
          params.value = stock;
          break;
        case 5:
          //   if (!businessId)return this.$message.error("请重新选择相同商户的产品");
          params = {
            ids: serverIds,
            departId: departIds[0] || "",
            firstDepartId: departIds[1] || "",
            secondDepartId: departIds[2] || "",
            thirdDepartId: departIds[3] || "",
            businessId,
          };
          await BusinessServerApi.batchSetDepart(params);
          break;
        case 6:
          if (!businessId)
            return this.$message.error("请重新选择相同商户的产品");
          params.classifyIds = classifyIds;
          await BusinessServerApi.batchSetRelation(params);
          break;
        case 7:
          params.value = deliveryWay;
          break;
        case 8:
          params.discountOld = discountOld
          params.discountPmc = discountPmc
          params.rebateOld = rebateOld
          params.rebatePmc = rebatePmc
          break;
      }
      if (type == 1 || type == 2 || type == 3 || type == 4 || type == 7 || type == 8)
        await BusinessServerApi.batchSetByType(params);
      this.$emit("confirm");
      this.$Utils.notifySuccess("设置成功！");
    },
    cancel() {
      this.$emit("showDialog", false);
    },
    numberVerify(i) {
      switch (i) {
        case 1: // 这里改为数字1
          if (this.discountOld < 0 || this.discountOld > 100 || !/^\d+(\.\d{1})?$/.test(this.discountOld)) { // 使用逻辑或
            this.discountOld = 0; // 设置默认值
            this.$message.error("抵扣金比例设置范围必须在0-100之间，并且最多只能有1位小数");
          }
          break;
        case 2: // 这里改为数字2
          if (this.discountPmc < 0 || this.discountPmc > 100 || !/^\d+(\.\d{1})?$/.test(this.discountPmc)) { // 使用逻辑或
            this.discountPmc = 0; // 设置默认值
            this.$message.error("抵扣金比例设置范围必须在0-100之间，并且最多只能有1位小数");
          }
          break;
        case 3: // 这里改为数字1
          if (this.rebateOld < 0 || this.rebateOld > 50 || !/^\d+(\.\d{1})?$/.test(this.rebateOld)) { // 使用逻辑或
            this.rebateOld = 0; // 设置默认值
            this.$message.error("返利比例设置范围必须在0-50之间，并且最多只能有1位小数");
          }
          break;
        case 4: // 这里改为数字1
          if (this.rebatePmc < 0 || this.rebatePmc > 50 || !/^\d+(\.\d{1})?$/.test(this.rebatePmc)) { // 使用逻辑或
            this.rebatePmc = 0; // 设置默认值
            this.$message.error("返利比例设置范围必须在0-50之间，并且最多只能有1位小数");
          }
          break;
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.business-classify_name,
.business-classify_select {
  ::v-deep p {
    margin: 0;

    img {
      vertical-align: middle;
      height: 16px;
      width: auto;
    }
  }
}

.el-dialog__wrapper {
  ::v-deep .el-dialog__body {
    padding: 40px !important;

    .item {
      margin: 10px;
      display: flex;
      line-height: 90px;

      .label {
        min-width: 120px;
        width: auto;
        max-width: 160px;
        margin-right: 10px;
      }

      .value {
        width: 300px;
      }
    }
  }
}
</style>
